package com.zoweunion.mechanic.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zoweunion.mechanic.dao.FacilitatorPersonnelRelationDao;
import com.zoweunion.mechanic.dao.app.ToolCarDataMapper;
import com.zoweunion.mechanic.entity.CarPersonEntity;
import com.zoweunion.mechanic.entity.CarTemplateBean;
import com.zoweunion.mechanic.entity.FacilitatorPersonnelRelationEntity;
import com.zoweunion.mechanic.model.app.AssignRegion;
import com.zoweunion.mechanic.plugins.redis.RedisUtil;
import com.zoweunion.mechanic.service.FacilitatorPersonnelRelationService;
import com.zoweunion.mechanic.service.app.ToolCarDataService;
import com.zoweunion.mechanic.service.app.impl.ToolCarDataServiceImpl;
import com.zoweunion.mechanic.service.base.LockCarService;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.gaode.AddressGEOUtil;
import jodd.http.HttpRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;


@Service("facilitatorPersonnelRelationService")
public class FacilitatorPersonnelRelationServiceImpl extends ServiceImpl<FacilitatorPersonnelRelationDao, FacilitatorPersonnelRelationEntity> implements FacilitatorPersonnelRelationService {

    @Autowired
    private FacilitatorPersonnelRelationDao facilitatorPersonnelRelationDao;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ToolCarDataService toolCarDataService;
    @Autowired
    private ToolCarDataServiceImpl toolCarDataServiceImpl;
    @Autowired
    private AddressGEOUtil addressGEOUtil;
    @Autowired
    private ToolCarDataMapper toolCarDataMapper;
    @Autowired
    private LockCarService lockCarService;

    public static final String servers = "_things_info";
    public static final String apiId = "Celadmin_putMachine_data*";
    public static final String apiSecret = "Celadmin_D&I*";
    public static final String Authorization = "Authorization";
    /* 测试
    public static final String getToken = "https://dni.cel-cat.com.cn/xcadmin/public/index.php/Api/getToken";
    public static final String pushDay = "https://dni.cel-cat.com.cn/xcadmin/public/index.php/Api/postDailyReport";
    public static final String pushMonth = "https://dni.cel-cat.com.cn/xcadmin/public/index.php/Api/postMonthReport";
    */
    public static final String getToken = "https://internal.cel-cat.com.cn/xcadmin/public/index.php/Api/getToken";
    public static final String pushDay = "https://internal.cel-cat.com.cn/xcadmin/public/index.php/Api/postDailyReport";
    public static final String pushMonth = "https://internal.cel-cat.com.cn/xcadmin/public/index.php/Api/postMonthReport";
    public static final String pushThingsId = "https://internal.cel-cat.com.cn/xcadmin/public/index.php/Api/postUnionCode";

    public static final String redisktbl = "CATOnlineThings_";


    @Override
    public PageInfo queryPage(Map<String, Object> map) {
        Integer pageSize = Integer.valueOf(map.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(map.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<FacilitatorPersonnelRelationEntity> mapList = facilitatorPersonnelRelationDao.queryPage(map);
        PageInfo<FacilitatorPersonnelRelationEntity> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    @Override
    public List<Map<String, Object>> getServerPhone(String mobilePhone) {
        return facilitatorPersonnelRelationDao.getServerPhone(mobilePhone);
    }

    @Override
    public List<Map<String, Object>> getServerAccountInfo(String serverAccount) {
        return facilitatorPersonnelRelationDao.getServerAccountInfo(serverAccount);
    }

    @Override
    public void updateUserRoleAdminAndaddFacilitator(Map<String, Object> reqMap) {
        String sId = this.addFacilitator(reqMap);
        //添加绑定关系


        this.updateUserRoleWithAdmin(sId, reqMap.get("userId").toString(), reqMap.get("update_user").toString());
        // 服务商添加管理区域
        List<AssignRegion> assignRegionList = this.wrapAddAssignRegionList(reqMap, sId);
        if (assignRegionList.size() > 0) {
            facilitatorPersonnelRelationDao.insertAssignRegion(assignRegionList);
        }
        //this.addFacilitatorAccount(reqMap); 添加服务商不需要向t_o_ss_user表中添加数据
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateUserRoleWithAdmin(String sId, String userId, String updateUser) {
        Map<String, Object> reqMap = new HashMap<>(6);
        reqMap.put("s_id", sId);
        reqMap.put("role_id", "7");
        reqMap.put("update_user", updateUser);
        reqMap.put("user_id", userId);
        facilitatorPersonnelRelationDao.updateUserRole(reqMap);
    }

    @Transactional(rollbackFor = Exception.class)
    public int addFacilitatorAccount(Map<String, Object> map) {
        map.put("id", UuidUtil.get32UUID());
        map.put("user_password", MD5.md5("123456"));
        map.put("status", 1);
        map.put("update_user", map.get("create_user"));
        this.insertUserRole(map.get("id").toString(), "09d2e9756c3d44c0acb1abe0e19b8b83",
                "e65a8deafbb14a0dadcc0375c937558b", map.get("create_user").toString());
        int result = facilitatorPersonnelRelationDao.insertUser(map);
        return 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public int insertUserRole(String userId, String roleId, String departmentId, String createUser) {
        Map<String, Object> userRole = new HashMap<>();
        userRole.put("id", UuidUtil.get32UUID());
        userRole.put("s_r_id", roleId);
        userRole.put("s_u_id", userId);
        userRole.put("s_d_id", departmentId);
        userRole.put("create_user", createUser);
        userRole.put("update_user", createUser);
        facilitatorPersonnelRelationDao.insertUserRole(userRole);
        return 1;
    }

    /**
     * 添加服务商
     */
    @Transactional(rollbackFor = Exception.class)
    public String addFacilitator(Map<String, Object> reqMap) {
        String sId = UuidUtil.get32UUID();
        reqMap.put("id", sId);
        if (!reqMap.containsKey("contact")){
            reqMap.put("contact", "");
        }
        if (!reqMap.containsKey("card_id")){
            reqMap.put("card_id", "");
        }
        reqMap.put("things_name", "");
        reqMap.put("server_type", 2);
        if (reqMap.containsKey("district_code")){
            Map<String, Object> location = AddressGEOUtil.getGPS(reqMap.get("location") + "");
            List geocodes = JSON.parseObject(location.get("geocodes").toString(), List.class);
            Map parseObject1 = JSON.parseObject(geocodes.get(0).toString(), Map.class);
            String s = (parseObject1.get("location").toString());
            List<String> result = Arrays.asList(s.split(","));
            reqMap.put("GPSlongitude", result.get(0));
            reqMap.put("GPSlatitude", result.get(1));
        }
        facilitatorPersonnelRelationDao.addFacilitator(reqMap);
        // 服务商添加管理区域
        List<AssignRegion> assignRegionList = this.wrapAddAssignRegionList(reqMap, sId);
        if (assignRegionList.size() > 0) {
            facilitatorPersonnelRelationDao.insertAssignRegion(assignRegionList);
        }
        return sId;
    }

    /**
     * 包装获取将要添加的管理区域列表
     *
     * @param reqMap
     * @param sId
     * @return
     */
    private List<AssignRegion> wrapAddAssignRegionList(Map<String, Object> reqMap, String sId) {
        List<AssignRegion> assignRegionList = new ArrayList<>();
        String createUser = reqMap.get("update_user").toString();
        if (reqMap.get("provinceList") != null) {
            List<Map<String, Object>> provinceList = (List<Map<String, Object>>) reqMap.get("provinceList");
            for (Map<String, Object> provinceObjMap : provinceList) {
                AssignRegion assignRegionProvince = new AssignRegion();
                assignRegionProvince.setProvinceName(provinceObjMap.get("name").toString());
                assignRegionProvince.setProvinceNumber(provinceObjMap.get("number").toString());
                if (provinceObjMap.get("cityList") != null) {
                    List<Map<String, Object>> cityList = (List<Map<String, Object>>) provinceObjMap.get("cityList");
                    if (cityList.size() == 0) {
                        this.wrapSetAssignRegionData(assignRegionProvince, createUser, sId);
                        assignRegionList.add(assignRegionProvince);
                        continue;
                    }
                    for (Map<String, Object> cityObjMap : cityList) {
                        AssignRegion assignRegionCity = new AssignRegion();
                        assignRegionCity.setProvinceName(provinceObjMap.get("name").toString());
                        assignRegionCity.setProvinceNumber(provinceObjMap.get("number").toString());
                        assignRegionCity.setCityName(cityObjMap.get("name").toString());
                        assignRegionCity.setCityNumber(cityObjMap.get("number").toString());
                        if (cityObjMap.get("areaList") != null) {
                            List<Map<String, Object>> areaList = (List<Map<String, Object>>) cityObjMap.get("areaList");
                            if (areaList.size() == 0) {
                                this.wrapSetAssignRegionData(assignRegionCity, createUser, sId);
                                assignRegionList.add(assignRegionCity);
                                continue;
                            }
                            for (Map<String, Object> areaObjMap : areaList) {
                                AssignRegion assignRegionArea = new AssignRegion();
                                assignRegionArea.setProvinceName(provinceObjMap.get("name").toString());
                                assignRegionArea.setProvinceNumber(provinceObjMap.get("number").toString());
                                assignRegionArea.setCityName(cityObjMap.get("name").toString());
                                assignRegionArea.setCityNumber(cityObjMap.get("number").toString());
                                assignRegionArea.setAreaName(areaObjMap.get("name").toString());
                                assignRegionArea.setAreaNumber(areaObjMap.get("number").toString());
                                this.wrapSetAssignRegionData(assignRegionArea, createUser, sId);
                                assignRegionList.add(assignRegionArea);
                            }
                        } else {
                            this.wrapSetAssignRegionData(assignRegionCity, createUser, sId);
                            assignRegionList.add(assignRegionCity);
                        }
                    }
                } else {
                    this.wrapSetAssignRegionData(assignRegionProvince, createUser, sId);
                    assignRegionList.add(assignRegionProvince);
                }
            }
        }
        return assignRegionList;
    }

    private void wrapSetAssignRegionData(AssignRegion assignRegion, String userId, String sId) {
        assignRegion.setId(UuidUtil.get32UUID());
        assignRegion.setsId(sId);
        assignRegion.setCreateUser(userId);
        assignRegion.setUpdateUser(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addFacilitatorUser(Map<String, Object> reqMap) {
        String serverSid = reqMap.get("server_sid").toString();

        // 根据主机厂的s_id获取给子服务商设置的轮播图的数量及设置，新增加的子服务商也需要联级更新设置信息 - add by qf-2022年1月22日12:48:03
        Map<String, Object> rotationChartSettingMap = facilitatorPersonnelRelationDao.getHasSetedFacilitatorSettingForAddFacilitatorOfRotationChart(serverSid);
        if(rotationChartSettingMap != null) {
            reqMap.put("picture_num", rotationChartSettingMap.get("picture_num") != null ? rotationChartSettingMap.get("picture_num").toString() : 0);
            reqMap.put("is_head", rotationChartSettingMap.get("is_head") != null ? rotationChartSettingMap.get("is_head").toString() : 0);
            reqMap.put("is_mid", rotationChartSettingMap.get("is_head") != null ? rotationChartSettingMap.get("is_head").toString() : 0);
        }

        String sId = this.addFacilitator(reqMap);  // 添加服务商表(t_s_ss_server)信息

        Map<String, Object> serverUserMap = new HashMap<String, Object>();
        serverUserMap.put("id", UuidUtil.get32UUID());
        serverUserMap.put("s_id", sId);
        serverUserMap.put("user_account", reqMap.get("server_account").toString());
        if (!reqMap.containsKey("user_password")){
            serverUserMap.put("user_password", MD5.md5("123456"));
        } else {
            serverUserMap.put("user_password", MD5.md5(reqMap.get("user_password").toString()));
        }
        serverUserMap.put("user_name", reqMap.get("server_account").toString());
        serverUserMap.put("r_id", "7");
        serverUserMap.put("mobile_phone", reqMap.get("mobile_phone").toString());
        serverUserMap.put("card_id", reqMap.get("card_id").toString());
        serverUserMap.put("status", 1);
        serverUserMap.put("delete_flag", 0);
        serverUserMap.put("create_user", reqMap.get("create_user").toString());
        serverUserMap.put("update_user", reqMap.get("update_user").toString());

        // 后市场账号
        facilitatorPersonnelRelationDao.addUserAccount(serverUserMap);

        // 添加主机厂绑定关系
        facilitatorPersonnelRelationDao.addServerRelation(serverSid, sId);

        // 添加权限
        reqMap.put("s_id", sId);
        this.setPermission(reqMap);
        // 添加服务商的管理区域
        List<AssignRegion> assignRegionNewList = this.wrapAddAssignRegionList(reqMap, sId);
        if (assignRegionNewList.size() > 0) {
            facilitatorPersonnelRelationDao.insertAssignRegion(assignRegionNewList);
        }
        //this.addFacilitatorAccount(serverUserMap); 注释掉现在不要往运营平台添加服务商用户 @DATE 2022/11/19
        return 1;
    }

    public void setPermission(Map<String, Object> reqMap) {
        List<String> pIds=null;
        if (reqMap.containsKey("contact")){
            //加权限
             pIds = Arrays.asList("w01","wc01-01","wc01-02",
                     "w02","wc02-01","wc02-02",
                     "w03","wc03-01","wc03-02","wc03-03","wc03-04",
                     "w07","wc07-01","wc07-03","wc07-04",
                     "w04", "wc04-05", "wc04-07", "wc04-11", "wc04-20", "wc04-25","wc04-30","wc04-35","wc04-40","wc04-45",
                     "w10",
                     "w06","wc06-01","wc06-08");
        }else {
            //加权限
             pIds = Arrays.asList("w04", "wc04-05", "wc04-07", "wc04-11", "wc04-20", "wc04-25","wc04-30","wc04-35","wc04-40","wc04-45", "wc15-02", "wc16-01", "w15",
                    "w16");
        }

        // 获取已有管理员服务商权限集合
        List<String> adminPermissions = facilitatorPersonnelRelationDao.listServerMenuPermission(reqMap.get("s_id").toString(), false);
        Map<String, Object> rolePermission = new HashMap<>(16);
        for (String pId : pIds) {
            if (!adminPermissions.contains(pId)) {
                rolePermission.put("id", UuidUtil.get32UUID());
                rolePermission.put("p_id", pId);
                rolePermission.put("s_id", reqMap.get("s_id"));
                rolePermission.put("r_id", "7");
                rolePermission.put("update_user", reqMap.get("update_user"));
                rolePermission.put("create_user", reqMap.get("update_user"));
                facilitatorPersonnelRelationDao.insertRoleServer(rolePermission);
            }
        }
    }

    @Override
    public Map<String, Object> getServerById(String id) {
        return facilitatorPersonnelRelationDao.getServerById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int edit(Map<String, Object> reqMap) {
        String sId = reqMap.get("id").toString();
        if (!reqMap.containsKey("contact")){
            reqMap.put("contact", "");
        }
        if (!reqMap.containsKey("card_id")){
            reqMap.put("card_id", "");
        }
        reqMap.put("things_name", "");
        if (reqMap.containsKey("district_code")){
            Map<String, Object> location = AddressGEOUtil.getGPS(reqMap.get("location") + "");
            List geocodes = JSON.parseObject(location.get("geocodes").toString(), List.class);
            Map parseObject1 = JSON.parseObject(geocodes.get(0).toString(), Map.class);
            String s = (parseObject1.get("location").toString());
            List<String> result = Arrays.asList(s.split(","));
            reqMap.put("GPSlongitude", result.get(0));
            reqMap.put("GPSlatitude", result.get(1));
        }

        // 更新服务商信息
        facilitatorPersonnelRelationDao.updateFacilitator(reqMap);
        // 获取服务商之前管理的区域
        List<AssignRegion> assignRegionOldList = facilitatorPersonnelRelationDao.selectAssignRegionFacilitatorBySId(sId);
        // 移除服务商的管理区域
        facilitatorPersonnelRelationDao.removeAssignRegionfacilitatorBySId(sId);
        // 添加服务商的管理区域
        List<AssignRegion> assignRegionNewList = this.wrapAddAssignRegionList(reqMap, sId);
        if (assignRegionNewList.size() > 0) {
            facilitatorPersonnelRelationDao.insertAssignRegion(assignRegionNewList);
        }
        // 移除服务商下被移除的管理区域下的员工负责区域
        List<AssignRegion> removeAssignRegionList = this.wrapRemovedAssginRegionList(assignRegionOldList, assignRegionNewList, sId);
        removeAssignRegionList.forEach(assignRegion -> facilitatorPersonnelRelationDao.removeAssignRegionWithFacilitatorBySId(assignRegion));
        return 1;
    }

    @Override
    public int delete(Map<String, Object> reqMap) throws MyException {
        //查询服务商下的物联网关编号
        int count = facilitatorPersonnelRelationDao.getThingsIdCount(reqMap);
        //查询服务商下的车辆
        count = count + facilitatorPersonnelRelationDao.getCarIdCount(reqMap);
        if (count >= 1) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "该服务商名下部分车辆仍未解绑，请解绑后再次尝试");
        }
        int result = 0;
        //删除服务商 车主车辆绑定表
        result += facilitatorPersonnelRelationDao.deleteFacilitatorOwnerCar(reqMap);
        //删除服务商 车辆绑定表
        result += facilitatorPersonnelRelationDao.deleteFacilitatorThings(reqMap);
        //删除服务商 车辆表
        result += facilitatorPersonnelRelationDao.deleteFacilitatorCar(reqMap);
        //删除服务商权限 角色权限表
        this.removeFacilitatorPermission(reqMap.get("id").toString(), reqMap.get("update_user").toString());
        //删除服务商 用户表
        this.updateUserRoleWithGuest(reqMap.get("id").toString(), reqMap.get("update_user").toString());
//		result += facilitatorDao.deleteFacilitatorUser(reqMap);
        // 移除服务商的所有负责区域，包括员工数据
        facilitatorPersonnelRelationDao.logicRemoveAssignRegionBySId(reqMap.get("id").toString());
        //删除服务商
        result += facilitatorPersonnelRelationDao.deleteFacilitator(reqMap);
        //删除绑定关系
        result += facilitatorPersonnelRelationDao.deleteFacilitatorRelation(reqMap);

        return result;
    }

    @Override
    public PageInfo facilitatorList(Map<String, Object> reqMap) {
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> mapList =
                facilitatorPersonnelRelationDao.facilitatorList(reqMap);
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void carPersonInsert(CarPersonEntity carPersonEntity) throws MyException {
        //新增车辆 判断thingsId 唯一
        String carId = UuidUtil.get32UUID();
        carPersonEntity.setId(carId);
        String entityThingsId = carPersonEntity.getThingsId();
        int thingsId = facilitatorPersonnelRelationDao.selectCarByThingsId(
                entityThingsId);
        if (thingsId == 0) {
            facilitatorPersonnelRelationDao.insertCar(carPersonEntity);
        } else {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "物联网编号重复,请重新选择");
        }
        //新增人员 判断 reqObj.put("user_password",
        for (Map<String, Object> item : carPersonEntity.getUserEntity()) {
            String userId = UuidUtil.get32UUID();
            item.put("id", userId);
            item.put("sid", carPersonEntity.getSid());
            item.put("userAccount", item.get("mobilePhone").toString());
            item.put("userPassword", MD5.md5("123456"));
            item.put("rId", Constants.ROLE_CZ);
            //插入人员信息
            int account = facilitatorPersonnelRelationDao.selectByUserAccount(item);
            if (account == 0) {
                facilitatorPersonnelRelationDao.insertUserInfo(item);
            } else {
                userId = facilitatorPersonnelRelationDao.selectByUserInfo(item);
            }
            //新增人脸 手机号,卡号
            int humanfaceByUser = facilitatorPersonnelRelationDao.selectHumanfaceByUser(
                    entityThingsId,
                    item.get("mobilePhone").toString());
            item.put("thingsId", entityThingsId);
            if (humanfaceByUser == 0) {
                facilitatorPersonnelRelationDao.insertUserInfoHuman(item);
            } else {
                facilitatorPersonnelRelationDao.updateUserInfoHuman(item);
            }
            item.put("carId", carId);
            item.put("userId", userId);
            item.put("thingsId", entityThingsId);
            facilitatorPersonnelRelationDao.insertRelation(item);
            //注册物联网号为绑定
            facilitatorPersonnelRelationDao.updateEquipmentType(entityThingsId,
                    carPersonEntity.getSid(), 0);//0为已注册
            //更新 为已发货
//            facilitatorPersonnelRelationDao.updateThingsDeliver(entityThingsId,
//                    carPersonEntity.getSid(), 1);//
        }
        //插入车主表,userId为空
        facilitatorPersonnelRelationDao.insertOwnerUser(UuidUtil.get32UUID(), carId,
                carPersonEntity.getSid());
    }

    @Override
    public PageInfo carList(Map<String, Object> reqMap) {
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> mapList =
                facilitatorPersonnelRelationDao.carList(reqMap);
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    @Override
    public List<Map<String, Object>> carInfo(Map<String, Object> reqMap) {
        List<Map<String, Object>> mapList =
                facilitatorPersonnelRelationDao.carInfo(reqMap);
        return mapList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void carDelete(Map<String, Object> reqMap) {
        facilitatorPersonnelRelationDao.carDelete(reqMap);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void carPersonUpdate(CarPersonEntity carPersonEntity) {
        facilitatorPersonnelRelationDao.updateCar(carPersonEntity);
        carPersonEntity.getUserEntity().forEach(item -> {

            item.put("sid", carPersonEntity.getSid());
            item.put("userAccount", item.get("mobilePhone").toString());
            item.put("userPassword", MD5.md5("123456"));
            item.put("rId", Constants.ROLE_CZ);
            item.put("thingsId", carPersonEntity.getThingsId());
            //插入人员信息
            if (!item.containsKey("id")) {
                String userId = UuidUtil.get32UUID();
                item.put("id", userId);
                facilitatorPersonnelRelationDao.insertUserInfo(item);
                item.put("carId", carPersonEntity.getId());
                item.put("userId", userId);
                facilitatorPersonnelRelationDao.insertRelation(item);

            } else {
                facilitatorPersonnelRelationDao.updateUserInfo(item);
            }
            List<Map<String, Object>> list = facilitatorPersonnelRelationDao.selectUserInfoHuman(item);
            if (list.size() != 0) {
                facilitatorPersonnelRelationDao.updateUserInfoHuman(item);
            } else {
                facilitatorPersonnelRelationDao.insertUserInfoHuman(item);
            }

        });
    }

    @Override
    public PageInfo facilitatorCarList(Map<String, Object> reqMap) {

        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void carListDelete(Map<String, Object> reqMap) {
        String id = Orgin.getString(reqMap, "id");
        Map<String, Object> map = facilitatorPersonnelRelationDao.selectCar(id);
        facilitatorPersonnelRelationDao.deleteFacilitatorOwnerCarById(reqMap);
        facilitatorPersonnelRelationDao.carDeleteInfo(reqMap);
        facilitatorPersonnelRelationDao.carListDelete(reqMap);
        //删除车辆物联网卡注册
        String thingsId = Orgin.getString(map, "things_id");
        String serverId = Orgin.getString(reqMap, "server_sid");
        facilitatorPersonnelRelationDao.updateEquipmentType(thingsId, serverId, 1);

    }

    @Override
    public List<Map<String, Object>> facilitatorByList(Map<String, Object> reqMap) {
        return facilitatorPersonnelRelationDao.facilitatorByList(reqMap);
    }

    @Override
    public PageInfo certificateList(Map<String, Object> map) {
        Integer pageSize = Integer.valueOf(map.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(map.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> mapList = facilitatorPersonnelRelationDao.certificateList(map);
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;

    }

    @Override
    public int certificateCount(Map<String, Object> map) {

        return facilitatorPersonnelRelationDao.certificateCount(map);
    }

    @Override
    public PageInfo carListCountAlarm(Map<String, Object> reqMap) {
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        String serverSid = Orgin.getString(reqMap, "server_sid");
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> mapList =
                facilitatorPersonnelRelationDao.carList(reqMap);
        mapList.forEach(item -> {
            String thingsId = Orgin.getString(item, "things_id");
            item.put("alarmCount", facilitatorPersonnelRelationDao.selectAlarm(thingsId));
            item.put("cerCount", facilitatorPersonnelRelationDao.selectCer(thingsId, serverSid));
        });
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    @Override
    public PageInfo alarmList(Map<String, Object> reqMap) {
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        String thingsId = Orgin.getString(reqMap, "things_id");
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> mapList =
                facilitatorPersonnelRelationDao.alarmList(thingsId);
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    @Override
    public PageInfo equipmentList(Map<String, Object> reqMap) {
        Integer pageSize = reqMap.get("pageSize") == null ? 999999999 : Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = reqMap.get("currentPage") == null ? 1 : Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> mapList = new ArrayList<>();
        if(reqMap.get("server_type") != null && reqMap.get("server_type").equals("3")){
            mapList = facilitatorPersonnelRelationDao.equipmentListAll(reqMap);
        }else {
            mapList = facilitatorPersonnelRelationDao.equipmentList(reqMap);
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(mapList);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertEquipmentList(List<String> reqMap, String sid, String pid) {
        reqMap.forEach(item -> {
            facilitatorPersonnelRelationDao.updateServiceThings(item, sid,pid);
        });
    }

    @Override
    public PageInfo equipmentListAll(Map<String, Object> reqMap) {
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> mapList =
                facilitatorPersonnelRelationDao.equipmentListAll(reqMap);
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEquipmentBatch(List<String> reqMap, String sid, String pSId) {
        reqMap.forEach(item -> {
            facilitatorPersonnelRelationDao.updateEquipmentBatch(item, sid, pSId);
        });
    }

    @Override
    public List<String> equipmentListRemove(Map<String, Object> reqMap) {
        return facilitatorPersonnelRelationDao.equipmentListRemove(reqMap);
    }

    @Override
    public List<Map<String, Object>> selectCarListCon(Map<String, Object> reqMap) {
        return facilitatorPersonnelRelationDao.selectCarListCon(reqMap);
    }

    @Override
    public void insertHuman(Map<String, Object> reqMap) {
        String things_id = Orgin.getString(reqMap, "things_id");
        Map<String, Object> map = facilitatorPersonnelRelationDao.selectHuman(things_id);
        if (map == null) {
            facilitatorPersonnelRelationDao.insertHuman(things_id);
        } else {
            facilitatorPersonnelRelationDao.updateHuman(Orgin.getIntValue(map, "id"));
        }
    }

    @Override
    public void updateHuman(Map<String, Object> reqMap) {
        facilitatorPersonnelRelationDao.updateHumanFaceId(reqMap);

    }

    @Override
    public Object uploadCarId(MultipartFile file) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
        try {
            byte[] imgData = file.getBytes();
            String imgStr = Base64.getEncoder().encodeToString(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "id_card_side=" + "front" + "&image=" + imgParam;
            String accessToken = PhoneCode.getAuth();
            String result = HttpUtil.post(url, accessToken, param);
            return JSONObject.parse(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeFacilitatorPermission(String sId, String updateUser) {
        Map<String, Object> reqMap = new HashMap<>(6);
        reqMap.put("s_id", sId);
        reqMap.put("update_user", updateUser);
        facilitatorPersonnelRelationDao.removeFacilitatorPermission(reqMap);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateUserRoleWithGuest(String sId, String updateUser) {
        Map<String, Object> reqMap = new HashMap<>(6);
        reqMap.put("s_id", sId);
        reqMap.put("role_id", "9");
        reqMap.put("update_user", updateUser);
        facilitatorPersonnelRelationDao.updateUserRoleBySId(reqMap);
    }


    /**
     * 获取要被删除的
     *
     * @param assignRegionOldList
     * @param assignRegionNewList
     * @param sId
     * @return
     */
    private List<AssignRegion> wrapRemovedAssginRegionList(List<AssignRegion> assignRegionOldList, List<AssignRegion> assignRegionNewList, String sId) {
        List<AssignRegion> removeAssignRegionList = new ArrayList<>();
        for (AssignRegion assignRegionOld : assignRegionOldList) {
            boolean hasProvince = false;
            boolean hasCity = false;
            for (AssignRegion assignRegionNew : assignRegionNewList) {
                // 如果含有省
                if (assignRegionOld.getProvinceNumber().equals(assignRegionNew.getProvinceNumber())) {
                    hasProvince = true;
                    if (assignRegionOld.getCityNumber() != null && assignRegionNew.getCityNumber() != null
                            && assignRegionOld.getCityNumber().equals(assignRegionNew.getCityNumber())) {
                        hasCity = true;
                        if (assignRegionOld.getAreaNumber() != null && assignRegionNew.getAreaNumber() != null
                                && assignRegionOld.getAreaNumber().equals(assignRegionNew.getAreaNumber())) {
                            break;
                        }
                    }
                }
                AssignRegion assignRegionNewObj = assignRegionNewList.get(assignRegionNewList.size() - 1);
                // 如果遍历到新区域列表的最后一个还没有，则移除当前省下的人员
                if (assignRegionNew.equals(assignRegionNewObj)) {
                    AssignRegion assignRegionParam = new AssignRegion();
                    assignRegionParam.setsId(sId);
                    if (!hasProvince) {
                        assignRegionParam.setProvinceNumber(assignRegionOld.getProvinceNumber());
                        removeAssignRegionList.add(assignRegionParam);
                    }
                    // 如果遍历到新区域列表的最后一个还没有，则移除当前省-市下的人员
                    if (!hasCity) {
                        assignRegionParam.setProvinceNumber(assignRegionOld.getProvinceNumber());
                        assignRegionParam.setCityNumber(assignRegionOld.getCityNumber());
                        removeAssignRegionList.add(assignRegionParam);
                    }
                    // 如果遍历到新区域列表的最后一个还没有，则移除当前省-市-区下的人员
                    if (hasProvince && hasCity) {
                        assignRegionParam.setProvinceNumber(assignRegionOld.getProvinceNumber());
                        assignRegionParam.setCityNumber(assignRegionOld.getCityNumber());
                        assignRegionParam.setAreaNumber(assignRegionOld.getAreaNumber());
                        removeAssignRegionList.add(assignRegionParam);
                    }
                }
            }
        }
        return removeAssignRegionList;
    }

    //根据主机厂获取子服务商sid
    private List<String> getServer(String sId) {
        return facilitatorPersonnelRelationDao.selectCountBySid(sId);
    }



    //获取分组后list
    private List<Map<String, Object>> getGroupList(Map<Integer, Long> serverMap) {
        List<Map<String, Object>> carList1 = new ArrayList<>();
        for (Map.Entry<Integer, Long> entry : serverMap.entrySet()) {
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("province_code", entry.getKey());
            hashMap.put("count", entry.getValue());
            carList1.add(hashMap);
        }
        return carList1;
    }

    //车辆redis

    public List<Map<String, Object>> getCarList(List<String> strings) {
        List<Map<String, Object>> carList = new ArrayList<>();
        strings.forEach(item -> {
            List<Map<String, Object>> list = new ArrayList<>();
            if (redisUtil.exists(item + servers)) {
                list = redisUtil.getList(item + servers);
            } else {
                //todo redis失效还原库里数据
                list = facilitatorPersonnelRelationDao.selectCarInfo(item);
                if (list.size()!=0){
                    redisUtil.insertList(list,item + servers);
                }
            }
            carList.addAll(list);
        });
        return carList;
    }

    //处理省市区搜索参数
    private int getCode(Map<String, Object> params) {
        int code = 0;
        if (params.containsKey("provinceCode")) {
            code = Orgin.getIntValue(params, "provinceCode");
        } else if (params.containsKey("cityCode")) {
            code = Orgin.getIntValue(params, "cityCode");
        } else if (params.containsKey("districtCode")) {
            code = Orgin.getIntValue(params, "districtCode");
        }
        return code;
    }

    //设备数/等
    private Map<String, Object> getCarCount(Map<String, Object> map,
                                        List<Map<String, Object>> carList) {
        //设备数
        map.put("carCount",carList.size());
        //在线
        Long status = carList.stream()
                .filter(o -> Orgin.getIntValue(o, "status") == 1).count();
        map.put("carOnline",status);
        //离线
        Long statusDown = carList.stream()
                .filter(o -> Orgin.getIntValue(o, "status") == 2).count();
        map.put("carDown",statusDown);
        //故障
        Long faultCount = carList.stream()
                .filter(o -> Orgin.getIntValue(o, "fault_status") == 1).count();
        map.put("faultCount",faultCount);
        //锁车
        Long lockCount = carList.stream()
                .filter(o -> Orgin.getIntValue(o, "lock_status") == 1).count();
        map.put("lockCount",lockCount);
        return map;
    }


    @Override
    public Map<String, Object> headCount(Map<String, Object> params) {
        Map<String, Object> map = new HashMap<>();
        String sId = Orgin.getString(params, "sid");
        //服务商总数
        List<String> strings = this.getServer(sId);
        map.put("serverCount", strings.size());
        //员工人数
        String serverString = "'" + StringUtils.join(strings, "','") + "'";
        long personCount = facilitatorPersonnelRelationDao.selectPersonCount(serverString);
        map.put("personCount", personCount);
        //车辆总数
        List<Map<String, Object>> carList = this.getCarList(strings);
        map.put("carCount", carList.size());
        //今日新增
        long carCountNow =
                facilitatorPersonnelRelationDao.selectCarCount(serverString, 1);
        map.put("carCountNow", carCountNow);
        map.put("now", LocalDateTime.now());
        return map;
    }

    @Override
    public Map<String, Object> mapForCarServer(Map<String, Object> params) {
        Map<String, Object> map = new HashMap<>();
        String sId = Orgin.getString(params, "sid");
        List<String> strings = this.getServer(sId);
        String serverString = "'" + StringUtils.join(strings, "','") + "'";
        List<Map<String, Object>> serverInfo =
                facilitatorPersonnelRelationDao.selectServerInfo(serverString);
        //服务商省分组总数
        Map<Integer, Long> serverMap = serverInfo.stream()
                .collect(Collectors.groupingBy(i -> Orgin.getInteger(i, "province_code"),
                        Collectors.counting()));
        //获取服务商分组后集合
        List<Map<String, Object>> serverList = new ArrayList<>();
        for (Map.Entry<Integer, Long> entry : serverMap.entrySet()) {
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("province_code", entry.getKey());
            hashMap.put("serverCount", entry.getValue());
            serverList.add(hashMap);
        }
        //查询车辆信息
        List<Map<String, Object>> carList = this.getCarList(strings);
        //车辆分组总数
        Map<Integer, Long> carMap = carList.stream()
                .collect(Collectors.groupingBy(i -> Orgin.getInteger(i, "province_code"),
                        Collectors.counting()));
        //获取车辆分组后集合
        List<Map<String, Object>> carList1 = new ArrayList<>();
        for (Map.Entry<Integer, Long> entry : carMap.entrySet()) {
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("province_code", entry.getKey());
            hashMap.put("carCount", entry.getValue());
            carList1.add(hashMap);
        }
        serverList.forEach(item -> {
            carList1.forEach(item1 -> {
                if (Orgin.getIntValue(item, "province_code") ==
                        Orgin.getIntValue(item1, "province_code")) {
                    item.put("carCount", Orgin.getInteger(item1, "carCount"));
                    item1.put("deleteFlag", 1);
                }
            });
        });
        carList1.addAll(serverList);
        List<Map<String, Object>> collect = carList1.stream()
                .filter(o -> !o.containsKey("deleteFlag"))
                .collect(Collectors.toList());
        //地图统计
        map.put("dataList",collect);
        //数量总数
        this.getCarCount(map,carList);
        return map;
    }

    @Override
    public Map<String, Object> mapForCarServerByPro(Map<String, Object> params) {
        Map<String, Object> hashMap = new HashMap<>();
        int code = this.getCode(params);
        String sId = Orgin.getString(params, "sid");
        List<String> strings = this.getServer(sId);
        String serverString = "'" + StringUtils.join(strings, "','") + "'";
        List<Map<String, Object>> serverInfo =
                facilitatorPersonnelRelationDao.selectServerInfo(serverString);
        int finalCode = code;
        List<Map<String, Object>> collect = serverInfo.stream()
                .filter(o -> Orgin.getIntValue(o, "province_code") == finalCode ||
                        Orgin.getIntValue(o, "city_code") == finalCode ||
                        Orgin.getIntValue(o, "district_code") == finalCode)
                .collect(Collectors.toList());
        hashMap.put("server", collect);
        //查询车辆信息
        List<Map<String, Object>> carList = this.getCarList(strings);
        List<Map<String, Object>> carCollect = carList.stream()
                .filter(o -> Orgin.getIntValue(o, "province_code") == finalCode ||
                        Orgin.getIntValue(o, "city_code") == finalCode ||
                        Orgin.getIntValue(o, "district_code") == finalCode)
                .collect(Collectors.toList());
        hashMap.put("car", carCollect);
        //数量总数
        this.getCarCount(hashMap,carCollect);
        return hashMap;
    }

    @Override
    public Map<String, Object> mapForCarServerBySid(Map<String, Object> params) {
        String sId = Orgin.getString(params, "s_id");
        List<String> strings = new ArrayList<>();
        int code = this.getCode(params);
        strings.add(sId);
        //查询车辆信息
        List<Map<String, Object>> carList = new ArrayList<>();
        carList = this.getCarList(strings);
        int finalCode = code;
        if (code != 0) {
            carList = carList.stream()
                    .filter(o -> Orgin.getIntValue(o, "province_code") == finalCode ||
                            Orgin.getIntValue(o, "city_code") == finalCode ||
                            Orgin.getIntValue(o, "district_code") == finalCode)
                    .collect(Collectors.toList());
        }
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("car", carList);
        //数量总数
        this.getCarCount(hashMap,carList);
        return hashMap;
    }

    @Override
    public Map<String, Object> carInfoByMap(Map<String, Object> params) {
        String things_id = Orgin.getString(params, "things_id");
        params.put("thingsId", things_id);
        //车辆实时数据
        Map<String, Object> map = toolCarDataService.selectMoreData(params);
        //车辆基础数据
        map.put("carInfo",facilitatorPersonnelRelationDao.selectInfoByCar(params));
        return map;
    }

    @Override
    public Map<String, Object> serverList(Map<String, Object> params) {
        Map<String, Object> map = new HashMap<>();
        String sId = Orgin.getString(params, "sid");
        List<String> strings = this.getServer(sId);
        String serverString = "'" + StringUtils.join(strings, "','") + "'";
        List<Map<String, Object>> serverInfo =
                facilitatorPersonnelRelationDao.selectServerInfo(serverString);
        serverInfo.forEach(item->{
            List<String> arrayList = new ArrayList<>();
            arrayList.add(Orgin.getString(item,"id"));
            List<Map<String, Object>> carList = this.getCarList(arrayList);
            //设备数
            item.put("carCount", carList.stream().count());
            //在线
            Long status = carList.stream()
                    .filter(o -> Orgin.getIntValue(o, "status") == 1).count();
            item.put("carOnline", status);
            //离线
            Long statusDown = carList.stream()
                    .filter(o -> Orgin.getIntValue(o, "status") == 2).count();
            item.put("carDown", statusDown);
            //故障
            Long faultCount = carList.stream()
                    .filter(o -> Orgin.getIntValue(o, "fault_status") == 1).count();
            item.put("faultCount", faultCount);
            //锁车
            Long lockCount = carList.stream()
                    .filter(o -> Orgin.getIntValue(o, "lock_status") == 1).count();
            item.put("lockCount", lockCount);
        });
        //服务商省分组总数
        Map<Integer, List<Map<String, Object>>> serverMap = serverInfo.stream()
                .collect(Collectors.groupingBy(i -> Orgin.getInteger(i, "province_code")));
        //获取服务商分组后集合
        List<Map<String, Object>> serverList = new ArrayList<>();
        for (Map.Entry<Integer, List<Map<String, Object>>> entry : serverMap.entrySet()) {
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("province_code", entry.getKey());
            List<Map<String, Object>> value = entry.getValue();
            hashMap.put("serverCount", value.size());
            int carCount = value.stream()
                    .mapToInt(o -> Orgin.getIntValue(o, "carCount")).sum();
            //设备数
            hashMap.put("carCount", carCount);

            int carOnline = value.stream()
                    .mapToInt(o -> Orgin.getIntValue(o, "carOnline")).sum();
            hashMap.put("carOnline", carOnline);

            int carDown = value.stream()
                    .mapToInt(o -> Orgin.getIntValue(o, "carDown")).sum();
            hashMap.put("carDown", carDown);

            int faultCount = value.stream()
                    .mapToInt(o -> Orgin.getIntValue(o, "faultCount")).sum();
            hashMap.put("faultCount", faultCount);

            int lockCount = value.stream()
                    .mapToInt(o -> Orgin.getIntValue(o, "lockCount")).sum();
            hashMap.put("lockCount", lockCount);
            serverList.add(hashMap);

        }
        //地图统计
        map.put("dataList", serverList);

        return map;
    }

    @Override
    public Map<String, Object> getFacilitatorInfo(String id) {
        Map<String, Object> serverMap = facilitatorPersonnelRelationDao.getFacilitatorInfo(id);
        // 获取服务商负责区域数据
        List<Map<String, String>> numbersMapList = facilitatorPersonnelRelationDao.selectAreaNumberAssignRegionFacilitatorBySId(serverMap.get("id").toString());
        String[] numbers = numbersMapList.stream().map(numbersMap -> numbersMap.get("areaNumberStr")).distinct().toArray(String[]::new);
        serverMap.put("areaNumbers", numbers);
        serverMap.put("provinceList", numbersMapList.size() == 0 ? Collections.emptyList() :
                this.wrapTreeWithAssignRegion(facilitatorPersonnelRelationDao.selectAssignRegionFacilitatorBySId(serverMap.get("id").toString())));
        return serverMap;
    }

    @Override
    public PageInfo manuList(Map<String, Object> reqMap) {
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> mapList =
                facilitatorPersonnelRelationDao.manuList(reqMap);
        PageInfo<Map<String, Object> > mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertManu(List<String> thingsIds, String sid) {
        thingsIds.forEach(item->{
            facilitatorPersonnelRelationDao.updateManu(item,sid);
        });
    }

    @Override
    public PageInfo manuListBySid(Map<String, Object> reqMap) {
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> mapList =
                facilitatorPersonnelRelationDao.manuListBySid(reqMap);
        PageInfo<Map<String, Object> > mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    @Override
    public void removeManu(List<String> thingsIds, String sid) {
        thingsIds.forEach(item->{
            facilitatorPersonnelRelationDao.removeManu(item,sid);
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertManuBySid(CarPersonEntity userEntity) throws MyException {
        for (Map<String, Object> item : userEntity.getUserEntity()) {
            int manuOnly = facilitatorPersonnelRelationDao.selectManuOnly(item);
            if (manuOnly > 0) {
                throw new MyException(Constants.CODE_HANDEL_FAILED,"制造编号重复");
            }
            int thingsOnly = facilitatorPersonnelRelationDao.selectThingsOnly(item);
            if (thingsOnly > 0) {
                throw new MyException(Constants.CODE_HANDEL_FAILED,"物联网关已绑定");
            }
            int i = facilitatorPersonnelRelationDao.selectManuSid(item);
            if (i > 0) {
                throw new MyException(Constants.CODE_HANDEL_FAILED,"请勿重复添加");
            }
            item.put("id",UuidUtil.get32UUID());
            item.put("sid",userEntity.getSid());
            facilitatorPersonnelRelationDao.insertManuSid(item);
            //更新物联网关为
            facilitatorPersonnelRelationDao.updateThingsRegister(Orgin.getString(item,"thingsId")
                    ,userEntity.getSid());
        }
    }

    @Override
    public void insertManuByFac(CarPersonEntity userEntity) {

    }

    @Override
    public PageInfo carBySid(Map<String, Object> reqMap) {
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        String sid = Orgin.getString(reqMap, "sid");
        List<String> strings = facilitatorPersonnelRelationDao.selectCountBySid(sid);
        strings.add(sid);
        String serverString = "'" + StringUtils.join(strings, "','") + "'";
        List<Map<String, Object>> mapList =
                facilitatorPersonnelRelationDao.carBySid(reqMap,serverString);
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteManuByFac(CarPersonEntity userEntity) {
        facilitatorPersonnelRelationDao.updateCarDelete(userEntity.getId(), userEntity.getSid());
        facilitatorPersonnelRelationDao.updateThingsDelete(userEntity.getThingsId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importCarList(List<CarTemplateBean> result,String sid) throws MyException {
        for (CarTemplateBean item : result) {
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("manufacturingNum",item.getManufacturingNum());
            hashMap.put("thingsId",item.getThingsId());
            int manuOnly = facilitatorPersonnelRelationDao.selectManuOnly(hashMap);
            if (manuOnly > 0) {
                throw new MyException(Constants.CODE_HANDEL_FAILED,"制造编号重复");
            }
            int thingsOnly = facilitatorPersonnelRelationDao.selectThingsOnly(hashMap);
            if (thingsOnly > 0) {
                throw new MyException(Constants.CODE_HANDEL_FAILED,"物联网关已绑定");
            }
            int thingsExit = facilitatorPersonnelRelationDao.selectThingsExit(item.getThingsId());
            if (thingsExit == 0) {
                throw new MyException(Constants.CODE_HANDEL_FAILED,"物联网关不存在");
            }
            if (thingsOnly > 0) {
                throw new MyException(Constants.CODE_HANDEL_FAILED,"物联网关已绑定");
            }
            int i = facilitatorPersonnelRelationDao.selectManuSid(hashMap);
            if (i > 0) {
                throw new MyException(Constants.CODE_HANDEL_FAILED,"请勿重复添加");
            }
            hashMap.put("id",UuidUtil.get32UUID());
            hashMap.put("sid",sid);
            facilitatorPersonnelRelationDao.insertManuSid(hashMap);
            //更新物联网关为已注册
            facilitatorPersonnelRelationDao.updateThingsRegister(item.getThingsId(),sid);
        }
    }

    @Override
    public PageInfo carForSid(Map<String, Object> reqMap) {

        return null;
    }

    /**
     * 把服务商负责区域数据封装为tree结构
     * @param assignRegionList
     * @return
     */
    private List<Map<String, Object>> wrapTreeWithAssignRegion(List<AssignRegion> assignRegionList) {
        List<Map<String, Object>> provinceList = new ArrayList<>();
        for (AssignRegion assignRegion : assignRegionList) {
            Map<String, Object> provinceMap = this.getMapByNumber(provinceList, assignRegion.getProvinceNumber());
            if (provinceMap == null) {
                provinceMap = new HashMap<>(5);
                provinceMap.put("number", assignRegion.getProvinceNumber());
                provinceMap.put("name", assignRegion.getProvinceName());
                provinceList.add(provinceMap);
            }
            if (assignRegion.getCityNumber() == null) {
                continue;
            }
            List<Map<String, Object>> cityList;
            if (provinceMap.get("cityList") != null) {
                cityList = (List<Map<String, Object>>) provinceMap.get("cityList");
            } else {
                cityList = new ArrayList<>(5);
                provinceMap.put("cityList", cityList);
            }

            Map<String, Object> cityMap = this.getMapByNumber(cityList, assignRegion.getCityNumber());
            if (cityMap == null) {
                cityMap = new HashMap<>();
                cityMap.put("number", assignRegion.getCityNumber());
                cityMap.put("name", assignRegion.getCityName());
                cityList.add(cityMap);
            }

            List<Map<String, Object>> areaList;
            if (cityMap.get("areaList") != null) {
                areaList = (List<Map<String, Object>>) cityMap.get("areaList");
            } else {
                areaList = new ArrayList<>(5);
                cityMap.put("areaList", areaList);
            }
            Map<String, Object> areaMap = this.getMapByNumber(areaList, assignRegion.getAreaNumber());
            if (areaMap == null) {
                areaMap = new HashMap<>();
                areaMap.put("number", assignRegion.getAreaNumber());
                areaMap.put("name", assignRegion.getAreaName());
                areaList.add(areaMap);
            }
        }
        return provinceList;
    }

    private Map<String, Object> getMapByNumber (List<Map<String, Object>> addressList, String number) {
        for (Map<String, Object> map : addressList) {
            if (map.get("number").toString().equals(number)) {
                return map;
            }
        }
        return null;
    }

    @Override
    public void pushDay() {

        Map tokenMap = this.getToken();
        String accessToken = Orgin.getString(tokenMap, "access_token");
        String tokenType = Orgin.getString(tokenMap, "token_type");

        //定义推送几号数据
        int day = 1;
        String date = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDateTime.now().minusDays(day));
        List<String> list =  redisUtil.getListString(redisktbl + date);
        Date dateNow = new Date();//获取当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateNow);
        calendar.add(Calendar.DATE, -day);
        List<Map<String, Object>> objects = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            String item = list.get(i);
            String table = toolCarDataServiceImpl.selectTableByThingsIdByDate(item, calendar.getTime());
            //查询昨天数据
            Map<String, Object> map1 = facilitatorPersonnelRelationDao.selectKtblDay(table + "_tb1", item,day);
            if (Orgin.getDoubleValue(map1,"working_time")<0.1){
                map1.put("working_time",0.0);
            }

//            // 查询油位数据
//            Map<String,Object> fuelGaugeMap = facilitatorPersonnelRelationDao.selectKtblDayFuelGaugeInfo(table + "_tb1", item,day);
//
//            if (fuelGaugeMap == null) {
//
//                map1.put("fuel_percen",0);
//            }else {
//
//                map1.putAll(fuelGaugeMap);
//            }

            //查询最后一条数据
            Map<String, Object> map4 = facilitatorPersonnelRelationDao.selectKtblDayInfo(table + "_tb1", item,day);
            //单独查询油位
            Map<String, Object> mapFuel = facilitatorPersonnelRelationDao.selectLastFuel(table + "_tb1", item, day);
            if (map4 == null) {
                // 昨天的数据定位可能有问题，需要查询实时表的经纬度数据
                Map<String, Object> realMap = toolCarDataMapper.selectRealDateGPS(item);
                if (realMap == null) {
                    continue;
                }else {
                    map4 = realMap;
                }
            }
            //查询最后一条源
            Map<String, Object> map5 = facilitatorPersonnelRelationDao.selectKtblDaySource(table + "_tb1", item,day);
            if (map1!=null&&map5 != null&&Orgin.getString(map4, "longitude") != null){
                if (Orgin.getDoubleValue(map1,"working_time")<0.1){
                    map1.put("working_time",0);
                }
                map1.putAll(map5);
                map1.putAll(map4);
                map1.put("fuel_percen",0.00);
                if (mapFuel!=null){
                    map1.putAll(mapFuel);
                }
                //获取最后一条地理位置
                String longitude = Orgin.getString(map4, "longitude");
                String latitude = Orgin.getString(map4, "latitude");
                String address = addressGEOUtil.getAddress(longitude, latitude);
                map1.put("m_location",address);
                map1.put("things_ids", item);
                //查询工作时段
                String dayWork = facilitatorPersonnelRelationDao.selectKtblDayWork(item,day);
                if (dayWork!=null){
                    map1.put("time_quantum", dayWork);
                }else {
                    map1.put("time_quantum","");
                }
                //经纬度
                objects.add(map1);
            }
        }

        redisUtil.insertListForString("objects "+objects.toString(),"cat:test");

        for (int i=0;i<objects.size();i+=20){
            Map<String, Object> map2 = new HashMap<>();
            List<Map<String, Object>> objectss = new ArrayList<>();
            if ((i+20)<objects.size()){
                objectss=objects.subList(i, i + 20);
                map2.put("list", objects.subList(i, i + 20).toArray());
            }else {
                objectss=objects.subList(i,objects.size());
                map2.put("list", objects.subList(i,objects.size()).toArray());
            }
            HttpRequest sendData;
            String bodyText="";
            Map bodyTe=null;
            //todo 推送完清除

            sendData =
                    HttpRequest.post(pushDay).bodyText(JSONObject.toJSONString(map2))
                            .contentType("application/json")
                            .charset("utf-8")
                            .header(Authorization, tokenType+" "+accessToken)
                            .host("internal.cel-cat.com.cn");


//            bodyText = sendData.send().bodyText();
//            bodyTe = JSON.parseObject(bodyText, Map.class);
//            String msg = Orgin.getString(bodyTe, "msg");



//            if (msg.equals("token error")){
//                Map tokenMap1 = this.getToken();
//                String accessToken1 = Orgin.getString(tokenMap1, "access_token");
//                String tokenType1 = Orgin.getString(tokenMap1, "token_type");
//                sendData =
//                        HttpRequest.post(pushDay).bodyText(JSONObject.toJSONString(map2))
//                                .contentType("application/json")
//                                .charset("utf-8")
//                                .header(Authorization, tokenType1+" "+accessToken1)
//                                .host("internal.cel-cat.com.cn");
//                bodyText = sendData.send().bodyText();
//                bodyTe = JSON.parseObject(bodyText, Map.class);
//            }


            //if (Orgin.getIntValue(bodyTe, "code") == 10000) {
                objectss.stream().map(x -> x.get("things_ids").toString()).
                        collect(Collectors.toList()).forEach(item1 -> {
                            //记录成功 删除key
                            redisUtil.removeList(redisktbl + date, item1);
                            facilitatorPersonnelRelationDao.insertDayLog(item1,"数据已处理",1,1);
                        });
                objectss.forEach(item1 -> {
                    //插入今日数据
                    facilitatorPersonnelRelationDao.insertDay(item1);
                });
            }
//            else {
//                objectss.stream().map(x -> x.get("things_ids").toString()).
//                        collect(Collectors.toList()).forEach(item1 -> {
//                            //记录失败
//                            facilitatorPersonnelRelationDao.insertDayLog(item1,msg,1,2);
//                        });
//            }
        //}
    }

    @Override
    public void pushMonth() {
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("api_id",apiId);
        hashMap.put("api_secret",apiSecret);
        //获取token
        HttpRequest httpRequest =
                HttpRequest.post(getToken).form(hashMap)
                        .contentType("application/x-www-form-urlencoded");
        String mapRouteString = httpRequest.send().bodyText();
        Map map = JSON.parseObject(mapRouteString, Map.class);
        Map tokenMap = JSON.parseObject(map.get("data").toString(), Map.class);
        String accessToken = Orgin.getString(tokenMap, "access_token");
        String tokenType = Orgin.getString(tokenMap, "token_type");
        //查询上月有统计数据
        List<Map<String, Object>> lastMonth = facilitatorPersonnelRelationDao.selectLastMonth();
        List<Map<String, Object>> objects = new ArrayList<>();
        lastMonth.forEach(item->{
            String thingsIds = Orgin.getString(item, "things_ids");
            Map<String, Object> map1 = facilitatorPersonnelRelationDao.selectCountMonth(thingsIds);
            if (Orgin.getDoubleValue(map1,"working_time")<0.1){
                map1.put("working_time",0.0);
            }
            double idelFuel = Orgin.getDoubleValue(map1, "idel_fuel");//当月怠速油耗
            Map<String, Object> map2 = facilitatorPersonnelRelationDao.selectCountMonthLast(thingsIds);
            map1.putAll(map2);
            //获取最后一条地理位置
            String longitude = Orgin.getString(map2, "longitude");
            String latitude = Orgin.getString(map2, "latitude");
            String address = addressGEOUtil.getAddress(longitude, latitude);
            map1.put("m_location",address);
            map1.put("things_ids",thingsIds);
            double f1=0.00;
            double totalFuel = Orgin.getDoubleValue(map2, "source_end_total_fuel");//当月怠速油耗
            if (totalFuel!=0d){
                BigDecimal bg = new BigDecimal( idelFuel / totalFuel*100);
                f1= bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            }
            map1.put("total_idel_fuel_percen",f1);
            objects.add(map1);
        });

        for (int i=0;i<objects.size();i+=20){
            Map<String, Object> map2 = new HashMap<>();
            List<Map<String, Object>> objectss = new ArrayList<>();
            if ((i+20)<objects.size()){
                objectss=objects.subList(i, i + 20);
                map2.put("list", objects.subList(i, i + 20).toArray());
            }else {
                objectss=objects.subList(i,objects.size());
                map2.put("list", objects.subList(i,objects.size()).toArray());
            }
            HttpRequest sendData;
            String bodyText="";
            Map bodyTe=null;
            //todo 推送完清除
            sendData =
                    HttpRequest.post(pushMonth).bodyText(JSONObject.toJSONString(map2))
                            .contentType("application/json")
                            .charset("utf-8")
                            .header(Authorization, tokenType+" "+accessToken)
                            .host("internal.cel-cat.com.cn");
            bodyText = sendData.send().bodyText();
            bodyTe = JSON.parseObject(bodyText, Map.class);
            String msg = Orgin.getString(bodyTe, "msg");
//            if (msg.equals("token error")){
//                Map tokenMap1 = this.getToken();
//                String accessToken1 = Orgin.getString(tokenMap1, "access_token");
//                String tokenType1 = Orgin.getString(tokenMap1, "token_type");
//                sendData =
//                        HttpRequest.post(pushMonth).bodyText(JSONObject.toJSONString(map2))
//                                .contentType("application/json")
//                                .charset("utf-8")
//                                .header(Authorization, tokenType1+" "+accessToken1)
//                                .host("internal.cel-cat.com.cn");
//                bodyText = sendData.send().bodyText();
//                bodyTe = JSON.parseObject(bodyText, Map.class);
//            }
            //if (Orgin.getIntValue(bodyTe, "code") == 10000) {
                objectss.stream().map(x -> x.get("things_ids").toString()).
                        collect(Collectors.toList()).forEach(item1 -> {
                            //记录成功
                            facilitatorPersonnelRelationDao.insertDayLog(item1,msg,2,1);
                        });
                objectss.forEach(item1 -> {
                    long l = facilitatorPersonnelRelationDao.selectByMonth(item1.get("things_ids").toString());
                    if (l==0l){
                        //插入今日数据
                        facilitatorPersonnelRelationDao.insertMonth(item1);
                    }//
                });
//            } else {
//                objects.stream().map(x -> x.get("serial_number").toString()).
//                        collect(Collectors.toList()).forEach(item1 -> {
//                            //记录失败
//                            facilitatorPersonnelRelationDao.insertDayLog(item1,msg,2,2);
//                        });
//            }
        }
    }

    @Override
    public void pushMoNiDay(int day) {
        Map tokenMap = this.getToken();
        String accessToken = Orgin.getString(tokenMap, "access_token");
        String tokenType = Orgin.getString(tokenMap, "token_type");
        //定义推送几号数据
        String date = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDateTime.now().minusDays(day));
        List<String> list =  redisUtil.getListString(Constants.CATMoNiThings + date);
        Date dateNow = new Date();//获取当前时间 
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateNow);
        calendar.add(Calendar.DATE, -day);
        List<Map<String, Object>> objects = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String item = list.get(i);
            String table = toolCarDataServiceImpl.selectTableByThingsIdByDate(item, calendar.getTime());
            //查询昨天数据
            Map<String, Object> map1 = facilitatorPersonnelRelationDao.selectKtblDay(table + "_tb1", item,day);
            if (Orgin.getDoubleValue(map1,"working_time")<0.1){
                map1.put("working_time",0.0);
            }
            //查询最后一条数据
            Map<String, Object> map4 = facilitatorPersonnelRelationDao.selectKtblDayInfo(table + "_tb1", item,day);
            //单独查询油位
            Map<String, Object> mapFuel = facilitatorPersonnelRelationDao.selectLastFuel(table + "_tb1", item, day);
            if (map4 == null) {
                // 昨天的数据定位可能有问题，需要查询实时表的经纬度数据
                Map<String, Object> realMap = toolCarDataMapper.selectRealDateGPS(item);
                if (realMap == null) {
                    continue;
                }else {
                    map4 = realMap;
                }
            }
            //查询最后一条源
            Map<String, Object> map5 = facilitatorPersonnelRelationDao.selectKtblDaySource(table + "_tb1", item,day);
            if (map1!=null&&map5 != null&&Orgin.getString(map4, "longitude") != null){
                if (Orgin.getDoubleValue(map1,"working_time")<0.1){
                    map1.put("working_time",0);
                }
                map1.putAll(map5);
                map1.putAll(map4);
                map1.put("fuel_percen",0.00);
                if (mapFuel!=null){
                    map1.putAll(mapFuel);
                }
                //获取最后一条地理位置
                String longitude = Orgin.getString(map4, "longitude");
                String latitude = Orgin.getString(map4, "latitude");
                String address = addressGEOUtil.getAddress(longitude, latitude);
                map1.put("m_location",address);
                map1.put("things_ids", item);
                //查询工作时段
                String dayWork = facilitatorPersonnelRelationDao.selectKtblDayWork(item,day);
                if (dayWork!=null){
                    map1.put("time_quantum", dayWork);
                }else {
                    map1.put("time_quantum","");
                }
                double today=0d;
                if (dayWork != null) {
                    HashMap workHoursMap = JSON.parseObject(dayWork, new TypeReference<HashMap<String, Object>>(){});
                    today = Orgin.getDoubleValue(workHoursMap, "workHours");
                }
                map1.put("total_time",today);
                if (Orgin.getDoubleValue(map1,"working_time")<0.1){
                    map1.put("working_time",0.0);
                }
                Map<String,Object> carInfo = toolCarDataMapper.getCarInfo(item);
                //查询模拟量总工时
                double countHour = facilitatorPersonnelRelationDao.selectCountHour(item);
                //车辆总工时
                String operatingHours = Orgin.getString(carInfo, "running");
                if (operatingHours!=null){
                    map1.put("source_end_total_time",countHour+Double.valueOf(operatingHours)+today);
                }
                //经纬度
                objects.add(map1);
            }
        }
        for (int i=0;i<objects.size();i+=20){
            Map<String, Object> map2 = new HashMap<>();
            List<Map<String, Object>> objectss = new ArrayList<>();
            if ((i+20)<objects.size()){
                objectss=objects.subList(i, i + 20);
                map2.put("list", objects.subList(i, i + 20).toArray());
            }else {
                objectss=objects.subList(i,objects.size());
                map2.put("list", objects.subList(i,objects.size()).toArray());
            }
            HttpRequest sendData;
            String bodyText="";
            Map bodyTe=null;
            //todo 推送完清除
            sendData =
                    HttpRequest.post(pushDay).bodyText(JSONObject.toJSONString(map2))
                            .contentType("application/json")
                            .charset("utf-8")
                            .header(Authorization, tokenType+" "+accessToken)
                            .host("internal.cel-cat.com.cn");
            bodyText = sendData.send().bodyText();
            bodyTe = JSON.parseObject(bodyText, Map.class);
            String msg = Orgin.getString(bodyTe, "msg");
            if (msg.equals("token error")){
                Map tokenMap1 = this.getToken();
                String accessToken1 = Orgin.getString(tokenMap1, "access_token");
                String tokenType1 = Orgin.getString(tokenMap1, "token_type");
                sendData =
                        HttpRequest.post(pushDay).bodyText(JSONObject.toJSONString(map2))
                                .contentType("application/json")
                                .charset("utf-8")
                                .header(Authorization, tokenType1+" "+accessToken1)
                                .host("internal.cel-cat.com.cn");
                bodyText = sendData.send().bodyText();
                bodyTe = JSON.parseObject(bodyText, Map.class);
            }
            if (Orgin.getIntValue(bodyTe, "code") == 10000) {
                objectss.stream().map(x -> x.get("things_ids").toString()).
                        collect(Collectors.toList()).forEach(item1 -> {
                    //记录成功 删除key
                    redisUtil.removeList(Constants.CATMoNiThings + date, item1);
                    facilitatorPersonnelRelationDao.insertDayLog(item1,msg,1,1);
                });
                objectss.forEach(item1 -> {
                    //插入今日数据
                    facilitatorPersonnelRelationDao.insertDay(item1);
                });
            } else {
                objectss.stream().map(x -> x.get("things_ids").toString()).
                        collect(Collectors.toList()).forEach(item1 -> {
                    //记录失败
                    facilitatorPersonnelRelationDao.insertDayLog(item1,msg,1,2);
                });
            }
        }
    }

    @Override
    public Map<String, Object> carInfoOwner(Map<String, Object> params) {
        return facilitatorPersonnelRelationDao.carInfoOwner(params);
    }

    @Override
    public void uploadLockLimit(Map<String, Object> reqMap) {
        facilitatorPersonnelRelationDao.uploadLockLimit(reqMap);
    }

    @Override
    public Map<String, Object> carInfoOwnerVideoInfo(Map<String, Object> params) {
        return facilitatorPersonnelRelationDao.carInfoOwnerVideoInfo(params);
    }

    @Override
    public int setFacilitatorCarLockPolicy(Map<String, Object> reqMap) {
        return facilitatorPersonnelRelationDao.setFacilitatorCarLockPolicy(reqMap);
    }

    @Override
    public int updateFacilitatorCarLockPolicy(Map<String, Object> reqMap) {
        return facilitatorPersonnelRelationDao.updateFacilitatorCarLockPolicy(reqMap);
    }

    @Override
    public int insertEquipmentListOfFinancial(Map<String, Object> reqMap) {
        //获取主机厂或服务商已经有的物联网卡数据
        List<Map<String, Object>> thingsList = facilitatorPersonnelRelationDao.getThingsList(reqMap);
        List<Map<String, Object>> reMapList = (List<Map<String, Object>>)reqMap.get("thingsList");
        for (Map<String, Object> things : reMapList) {
            for (Map<String, Object> thingsMap : thingsList) {
                if (com.alibaba.druid.util.StringUtils.equals(thingsMap.get("things_id").toString(), things.get("things_id").toString())) {
                    return 2;
                }
            }
            Map<String, Object> thingsMap = new HashMap<String, Object>();
            thingsMap.put("s_id", reqMap.get("s_id"));
            thingsMap.put("things_id", things.get("things_id"));
            thingsMap.put("financial_id", reqMap.get("financial_id"));
            //thingsMap.put("opc_path", things.get("opc_path"));
            thingsMap.put("update_user", reqMap.get("update_user"));
            if (reqMap.containsKey("server_type") &&
                    Orgin.getIntValue(reqMap, "server_type") == 1) {
                facilitatorPersonnelRelationDao.updateParentThings(thingsMap);
            } else {
                facilitatorPersonnelRelationDao.updateNewThings(thingsMap);
            }
        }
        return 1;
    }

    @Override
    public void deleteEquipmentBatchOfFinancial(Map<String, Object> reqMap) {
        facilitatorPersonnelRelationDao.updateEquipmentBatchOfFinancial(reqMap);
    }

    @Override
    public PageInfo getCarOwnerApplyUnlockList(Map<String, Object> reqMap) {
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> mapList = facilitatorPersonnelRelationDao.getCarOwnerApplyUnlockList(reqMap);
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOwnerApplyUnlockById(Map<String, Object> reqMap) {
        int result = facilitatorPersonnelRelationDao.updateOwnerApplyUnlockById(reqMap);
        if(reqMap.get("apply_status") != null && reqMap.get("apply_status").equals(1)){
            //如果通过，则直接解锁车辆
            reqMap.put("lock_user_id", reqMap.get("user_id").toString());
            reqMap.put("update_user", reqMap.get("user_id").toString());
            reqMap.put("s_id", reqMap.get("s_id").toString());
            reqMap.put("user_name", reqMap.get("userName").toString());
            reqMap.put("smsStatus", "1");
            reqMap.put("isLocked", "0");
            reqMap.put("lock_type", 3);
            reqMap.put("car_id", reqMap.get("c_id").toString());
            lockCarService.thingsIdCarOperation(reqMap);
        }
        return result;
    }


    @Override
    public void pushThingsId() {
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("api_id",apiId);
        hashMap.put("api_secret",apiSecret);
        //获取token
        HttpRequest httpRequest =
                HttpRequest.post(getToken).form(hashMap)
                        .contentType("application/x-www-form-urlencoded");
        String mapRouteString = httpRequest.send().bodyText();
        Map map = JSON.parseObject(mapRouteString, Map.class);
        Map tokenMap = JSON.parseObject(map.get("data").toString(), Map.class);
        String accessToken = Orgin.getString(tokenMap, "access_token");
        String tokenType = Orgin.getString(tokenMap, "token_type");
        Map<String, Object> map2 = new HashMap<>();
        List<Map<String, Object>> list =facilitatorPersonnelRelationDao.selectKtThingsIds();
        map2.put("list",list);
        HttpRequest sendData =
                HttpRequest.post(pushThingsId).bodyText(JSONObject.toJSONString(map2))
                        .contentType("application/json")
                        .charset("utf-8")
                        .header(Authorization, tokenType+" "+accessToken)
                        .host("internal.cel-cat.com.cn");
        String bodyText = sendData.send().bodyText();
        Map bodyTe = JSON.parseObject(bodyText, Map.class);
        String msg = Orgin.getString(bodyTe, "msg");
    }



    public Map<String,Object> getToken(){
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("api_id",apiId);
        hashMap.put("api_secret",apiSecret);

        //获取token
        HttpRequest httpRequest =
                HttpRequest.post(getToken).form(hashMap)
                        .contentType("application/x-www-form-urlencoded");
        String mapRouteString = httpRequest.send().bodyText();
        Map map = JSON.parseObject(mapRouteString, Map.class);

        return JSON.parseObject(map.get("data").toString(), Map.class);
    }
}
